﻿using System;
using System.IO;
using System.Text;

namespace Sencha.Serialization
{
	public sealed class JsonStreamWriter : JsonWriterBase
	{
		StreamWriter m_writer;

		public Stream Stream { get { return m_writer.BaseStream; } }
		private StreamWriter Writer { get { return m_writer; } }

		public JsonStreamWriter(Stream stream)
			: this(stream, new AdHocSerializer())
		{

		}
		public JsonStreamWriter(Stream stream, ISerializationContext context)
			: base(context)
		{
			if (stream == null)
				throw new ArgumentNullException("stream");
			if (!stream.CanWrite)
				throw new Exceptions.UnwriteableStream("stream");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			m_writer = new StreamWriter(stream, context.Encoding);
		}

		public override void Flush()
		{
			m_writer.Flush();
		}
		public override void WriteJson(string jsonString)
		{
			if (jsonString == null)
				throw new ArgumentNullException("jsonString");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			m_writer.Write(jsonString);
			this.CharactersWritten += jsonString.Length;
		}
		public override void WriteJson(char[] jsonString, int index, int charactersToWrite)
		{
			if (jsonString == null)
				throw new ArgumentNullException("jsonString");
			if (index < 0 || index >= jsonString.Length)
				throw new ArgumentOutOfRangeException("index");
			if (charactersToWrite < 0 || index + charactersToWrite > jsonString.Length)
				throw new ArgumentOutOfRangeException("charactersToWrite");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			if (charactersToWrite == 0)
				return;
			m_writer.Write(jsonString, index, charactersToWrite);
			this.CharactersWritten += charactersToWrite;
		}
	}
}
